package models

import "gorm.io/gorm"

type Cart struct {
	gorm.Model
	ProductID uint     `json:"product_id" binding:"required"`
	Count     int      `json:"count" binding:"required"`
	UserID    uint     `json:"user_id" binding:"required"`
	db        *gorm.DB `json:"-"`
}

func (Cart) TableName() string {
	return "carts"
}

type ICart interface {
	FindByID(cartId uint) (*Cart, error)
	FindByUserID(page, rows int, userId uint) (pages *Pages, error error)
	Create(c *Cart) (*Cart, error)
	Update(c *Cart) (*Cart, error)
	Delete(cartId int) error
}

func NewCart(db *gorm.DB) ICart {
	return &Cart{db: db}
}
func (p *Cart) FindByID(cart_id uint) (model *Cart, err error) {
	model = &Cart{}
	model.ID = cart_id
	result := p.db.First(model)
	err = result.Error
	return
}
func (p Cart) FindByUserID(page, rows int, user_id uint) (pages *Pages, error error) {
	var data []Cart
	var all int64
	pages = &Pages{}
	query := p.db.Model(Cart{}).Where("user_id = ?", user_id)
	//all
	result := query.Count(&all)
	if result.Error != nil {
		return nil, result.Error
	}
	query.Limit(rows).Offset((page - 1) * rows).Find(&data)
	result = query.Count(&all)
	if result.Error != nil {
		return nil, result.Error
	}
	return NewPages(page, rows, all, data), nil
}

func (p *Cart) Create(c *Cart) (*Cart, error) {
	result := p.db.Create(c)
	if result.Error != nil {
		return nil, result.Error
	}
	return c, nil
}

func (p *Cart) Update(c *Cart) (*Cart, error) {
	result := p.db.Updates(c)
	if result.Error != nil {
		return nil, result.Error
	}
	return c, nil
}

func (p *Cart) Delete(cartId int) error {
	result := p.db.Delete(&Cart{}, cartId)
	return result.Error
}
